package com.zhu.ttwords.common;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.zhu.ttwords.TTWORDS;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by KnightYe on 2015/4/5.
 * 数据库存储工具类。将来可能替换成开源api库
 */
public class DBTool {
    static File databaseDir;
    static SQLiteDatabase db;
    static File dBFile;

    public static SQLiteDatabase getDatabase() {
        if (db == null) {
            db = SQLiteDatabase.openOrCreateDatabase(dBFile, null);
        }
        return db;
    }

    public static void deleteDB() {
        dBFile = new File(databaseDir, TTWORDS.DATABASE_NAME);
        if (dBFile.exists()) {
            boolean result = dBFile.delete();
            Log.d("DBTool", "Database TTWORDS.db deleted result is：" + result);
        }
    }

    /**
     * 检查数据库路径,如果有SD卡，缓存存到卡上，如果没有，则存到缓存目录上
     */
    public static void initDatabaseDir(Context context) {

        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            databaseDir = new File(
                    android.os.Environment.getExternalStorageDirectory(), TTWORDS.DATABASE_DIR);
        } else {
            databaseDir = context.getCacheDir();
        }
        Log.d("DBTool", "File dir is" + databaseDir.getAbsolutePath());
        if (!databaseDir.exists()) {
            boolean result = databaseDir.mkdirs();
            Log.d("DBTool", "Database dir init result is：" + result);
        }
    }


    /**
     * 检查数据库文件，如果没有，则从内存中写入
     */
    public static boolean initDatabaseFile(Context context) {
        dBFile = new File(databaseDir, TTWORDS.DATABASE_NAME);
        boolean hasDB = dBFile.exists();
        if (!hasDB) {
            try {
                //从内存中取出数据库.db文件
                InputStream localInputStream = context.getAssets().open(TTWORDS.DATABASE_NAME);
                //建立通向SD卡通道
                FileOutputStream localFileOutputStream = new FileOutputStream(dBFile);
                //写入数据库
                byte[] arrayOfByte = new byte[1024];
                while (true) {
                    int i = localInputStream.read(arrayOfByte);
                    if (i <= 0) {
                        localFileOutputStream.flush();
                        localFileOutputStream.close();
                        localInputStream.close();
                        break;
                    }
                    localFileOutputStream.write(arrayOfByte, 0, i);
                }
                Log.d("DBTool", "DB file writed!");
                //更新版本号。数据库版本号和APP的versionCode保持一致
                TTWORDS.getAppSetting().setVersionCode(TTWORDS.getVersionCode());
                TTWORDS.getAppSetting().setVersionName(TTWORDS.getVersionName());
            } catch (IOException localIOException) {
                localIOException.printStackTrace();
            }
        }
        return hasDB;
    }

    /**
     * **********************************************************
     */


    public static Object getSingleBean(Class<?> clazz, String sql) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return getSingleBean(clazz, sql, null);
    }

    public static Object getSingleBean(Class<?> clazz, String sql, String[] params) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        List<Object> list = getDataBean(clazz, sql, params);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    public static List<Object> getDataBean(Class<?> clazz, String sql) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return getDataBean(clazz, sql, null);
    }

    public static List<Object> getDataBean(Class<?> clazz, String sql, String[] params) throws InstantiationException,
            IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        List<Object> list = new ArrayList<>();
        Cursor cur = getDatabase().rawQuery(sql, params);
        while (cur.moveToNext()) {
            list.add(CursorUtil.cursorToBean(cur, clazz));
        }
        cur.close();
        return list;
    }

    public static long count(String sql, String[] params) {
        long result;
        Cursor cur = getDatabase().rawQuery(sql, params);
        cur.moveToNext();
        result = cur.getLong(0);
        cur.close();
        return result;
    }

    public static long saveBeanData(Object bean) {
        try {
            return getDatabase().replace("TT_REPERTORY", "UID", CursorUtil.beanToContentValues(bean));
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static long saveBeanData(String table, String nullColumnHack, Object bean) {
        try {
            return getDatabase().replace(table, nullColumnHack, CursorUtil.beanToContentValues(bean));
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return -1;
    }


}
